//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// 			VisualNovelToolkit		     /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe.	/_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Animation Manager.
/// Collect AnimationNode and PlayAnimation by Key.
/// </summary>
[ System.Serializable ]
public class ViNoAnimationManager : MonoBehaviour {
	static private ViNoAnimationManager m_Instance;
	public static ViNoAnimationManager Instance {
		get {	return ViNoAnimationManager.m_Instance;	}
	}

	public string[] animNames;

	private AnimationNode[] animations;
	private Dictionary<string,int> m_AnimTable;

	void Awake(){
		if( m_Instance == null ){
			m_Instance =  this;
			CollectAnimationNames();
		}
		else{
			Destroy( gameObject );
		}
	}

	// Collect AnimationNodes in this object and this Children Components.
	public void CollectAnimationNames(){
		m_AnimTable = new Dictionary<string,int>();
	  	animations = GetComponentsInChildren<AnimationNode>();
	  	List<string> animNameList = new List<string>();
		for(int i=0;i<animations.Length;i++){
			string key = animations[ i ].animationName;			
			if( animations[ i ].enabled ){
				if( animations[ i ].animTarget != null ){
					if( ! string.IsNullOrEmpty( key ) ){
						animNameList.Add( key );
						m_AnimTable.Add( key , i );
					}
				}
/*				else{
					Debug.LogError( "animation Named: "+ key + " target not Set." );
				}
//*/				
			}
		}
		animNames = animNameList.ToArray();
	}

	public void PlayAnimation( int index ){
		ViNoDebugger.Log( "ANIMATION" , "Play Animation at Index: " + index.ToString() + "=" + animations[ index ].animationName );
		animations[ index ].Preview();		
	}

	public AnimationNode PlayAnimation( string animName ){
		if( m_AnimTable.ContainsKey( animName ) ){
			int animationIndex = m_AnimTable[ animName ];
			animations[ animationIndex ].Preview();
			return animations[ animationIndex ];
		}
		else{
			return null;
		}
	}

	// if not found return -1.
	public int GetAnimationIDBy( string animName ){
		for( int i=0;i<animNames.Length;i++){
			if( animNames[ i ].Equals( animName ) ){
				return i;
			}
		}
		return -1;
	}

}
